//
//  DiscoveryViewController.m
//  PigMarket
//
//  Created by Felix on 2019/3/4.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "DiscoveryViewController.h"
#import "RecentlyChatListViewController.h"
#import "PersonalInfomationViewController.h"
#import "DiscoveryActicleListViewController.h"
#import "ChatViewController.h"
#import "XXTGHomeWebViewController.h"

#import "NearbyFriendCell.h"
#import "DiscoveryHeaderView.h"
#import "DiscoveryWebViewController.h"
#import "FoundServiceViewController.h"


@interface DiscoveryViewController ()

@property (nonatomic, strong) DiscoveryHeaderView *headerView;
@property (nonatomic, assign) double longitude;
@property (nonatomic, assign) double latitude;
@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, strong) NSArray *acticles;

@end

@implementation DiscoveryViewController

#pragma mark - lifecycle methods

- (void)setupUI{
    
    {
        self.baseNavView.line.hidden = YES;
        self.baseNavView.leftNavBtn.hidden = YES;
    }
    
    {
        [self initAction];
        [self requestQsActicleTitles];
    }
}


- (void)setupLayout{
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.bottom.mas_equalTo(0);
        make.top.mas_equalTo(self.baseNavView.bottom - 40);
    }];
}



- (void)initData {
    //广告轮播请求
    [self bannerRequest];
    
    //定位
    @weakify(self);
    [[LocationManager sharedManager] startLocationCompleteBlock:^(double latitude, double longitude) {
        @strongify(self);
        self.longitude = longitude;
        self.latitude = latitude;
        
        [self dataRequest];
    }];
}


#pragma mark - networking methods

- (void)dataRequest{
    
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    
    //未登录状态
    if ([JTool iSNull:memberId]) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        return;
    }
    
    NearbyFriendsParam *param = [[NearbyFriendsParam alloc] init];
    param.page = self.page ;
    param.limit = 10;
    double longitude = self.longitude ? self.longitude : 0;
    double latitude = self.longitude ? self.latitude : 0;
    
    param.longitude = [NSString stringWithFormat:@"%f",longitude];
    param.latitude = [NSString stringWithFormat:@"%f",latitude];
    param.memberId = memberId;
    NSNumber *sexType = @0;
    if (self.headerView.allBtn.selected) {
        sexType = @0;
    } else if (self.headerView.manBtn.selected) {
        sexType = @1;
    } else if (self.headerView.womanBtn.selected) {
        sexType = @2;
    }
    param.sex = sexType;//0是全部  1男 2女
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] nearbyFriendsWithParam:param] subscribeNext:^(NearbyFriendsList * _Nullable nearbyFriendsList) {
        @strongify(self);
        
        if (self.isRefresh) {
            
            [self endRefresh];
            if (self.datas.count >0) {
                [self.datas removeAllObjects];
            }
        }
        
        [nearbyFriendsList.list enumerateObjectsUsingBlock:^(NearbyFriends * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.datas addObject:obj];
        }];
        
        if ([nearbyFriendsList.currPage intValue] >= [nearbyFriendsList.totalPage intValue]) {
            [self endLoadMoreMoData];
        }else{
            [self endLoadMore];
        }
        
        if (self.datas.count >0) {
            self.tableView.hidden = NO;
            [self.tableView reloadData];
        }else{
            [self loadNoData];
        }
        
    }error:^(NSError * _Nullable error) {
        @strongify(self);
        [self loadErrorData];
    }];
}

//下拉刷新
- (void)refresh
{
    [super refresh];
    [self resetData];
    [self initData];
}

//上拉加载更多
- (void)loadMore
{
    [super loadMore];
    [self dataRequest];
}


//广告轮播
- (void)bannerRequest {
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] getDiscoveryAdvertising] subscribeNext:^(MessageList * _Nullable messageList) {
        @strongify(self);
        NSMutableArray *tempArr = [[NSMutableArray alloc] init];
        for (Message *model in messageList.list) {
            [tempArr addObject:model.imgName];
        }
        self.headerView.cycleView.imageURLStringsGroup = tempArr;
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (void)requestQsActicleTitles{
    
   __block NSMutableArray *array = [NSMutableArray array];
    @weakify(self);
    [[[MeatFoundApi sharedInstance] getArticleTypeList] subscribeNext:^(FoundActicleTypeModel * _Nullable model) {
        @strongify(self);
        [model.list enumerateObjectsUsingBlock:^(FoundActicleTypeItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [array addObject:obj];
        }];
        
        FoundActicleTypeItem *item = [[FoundActicleTypeItem alloc] init];
        item.text = @"全部";
        item.value = @0;
        [array insertObject:item atIndex:0];
        
        self.acticles = [array copy];
    }];
}


//我想聊聊
- (void)chat {
    
    //校验聊天是否登陆成功，否则重新登录
    if ([UserInfoDataProvider sharedInstance].userInfo.isIMLogin) {
        
        @weakify(self);
        [self pushToViewController:^{
            @strongify(self);
            [self.navigationController pushViewController:[[RecentlyChatListViewController alloc] init] animated:YES];
        }];
        
    } else {
        //如果没登录过
        NSString *userSig = [UserInfoDataProvider sharedInstance].userInfo.userSig;
        NSString *userName = [UserInfoDataProvider sharedInstance].userInfo.memberNum;
        [[ChatManager sharedInstance] loginIMWithUserName:userName userSig:userSig succ:^{
            [self toastWithContent:@"聊天登录成功"];
            UserInfo *userInfo = [UserInfoDataProvider sharedInstance].userInfo;
            userInfo.isIMLogin = YES;
            [UserInfoDataProvider sharedInstance].userInfo = userInfo;
        } fail:^(int code, NSString * _Nonnull msg) {
            [self toastWithContent:msg];
        }];
        [self.navigationController pushViewController:[[RecentlyChatListViewController alloc] init] animated:YES];
    }
}


//聊天
- (void)beginChatWithIdentifier:(NSString *)identifier {
    TUIConversationCellData *data = [[TUIConversationCellData alloc] init];
    data.convId = identifier;
    data.convType = TIM_C2C;
    data.title = identifier;
    ChatViewController *chat = [[ChatViewController alloc] init];
    chat.conversation = data;
    [self.navigationController pushViewController:chat animated:YES];
}


#pragma mark - response methods

- (void) initAction {
    
    [self.headerView.allBtn addTarget:self action:@selector(allBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView.manBtn addTarget:self action:@selector(manBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView.womanBtn addTarget:self action:@selector(womanBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    //我想聊聊
    @weakify(self);
    self.headerView.dealMessageBlock = ^{
        @strongify(self);
        [self chat];
    };
    
    //清饲生活
    self.headerView.dealLifeBlock = ^{
        @strongify(self);
        
        if (self.acticles.count >0) {
            DiscoveryActicleListViewController *vc = [[DiscoveryActicleListViewController alloc] init];
            vc.titles = self.acticles;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [self showHudWithMsg:@"暂无清饲文章"];
        }
    };
    
    //服务地图
    self.headerView.dealServiceBlock = ^{
        @strongify(self);
        //[self clickOnlineServiceButton];
        FoundServiceViewController *vc = [[FoundServiceViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    };
    
}

- (void)clickHelpCenterButton
{
    //点击商户帮助中心
    XXTGHomeWebViewController * vc = [[XXTGHomeWebViewController alloc]init];
    vc.urlString = [NSString stringWithFormat:@"%@%@",URL_HTML_Server,@"lizhenhu/app_feedback/index.html"];
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)clickOnlineServiceButton
{
    //点击在线客服
    DiscoveryWebViewController * vc = [[DiscoveryWebViewController alloc]init];
    vc.urlString = URL_HTML_MineOnlineCustomerServiceURL;
    [self.navigationController pushViewController:vc animated:YES];
}



- (void)allBtnClick:(UIButton *)button {
    self.headerView.allBtn.selected = YES;
    self.headerView.manBtn.selected = NO;
    self.headerView.womanBtn.selected = NO;
    self.page = 1;
    [self.datas removeAllObjects];
    [self dataRequest];
}

- (void)manBtnClick:(UIButton *)button {
    self.headerView.manBtn.selected = YES;
    self.headerView.allBtn.selected = NO;
    self.headerView.womanBtn.selected = NO;
    self.page = 1;
    [self.datas removeAllObjects];
    [self dataRequest];
}

- (void)womanBtnClick:(UIButton *)button {
    self.headerView.womanBtn.selected = YES;
    self.headerView.allBtn.selected = NO;
    self.headerView.manBtn.selected = NO;
    self.page = 1;
    [self.datas removeAllObjects];
    [self dataRequest];
}


#pragma mark - tableview.datasource methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.datas.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 0.01;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return [[UIView alloc] init];
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NearbyFriendCell *cell = [NearbyFriendCell cellWithTableView:tableView];
    if (self.datas.count > indexPath.row) {
        NearbyFriends *model = self.datas[indexPath.section];
        
        cell.model = model;
        //聊一聊  or  加好友
        @weakify(self);
        [cell setAddOrChatBlock:^(AddFriendOrChatType addFriendOrChatType) {
            @strongify(self);
            if (addFriendOrChatType == AddFriendOrChatTypeAdd) {
                
                //添加好友
                AddFriendVerifyViewController *vc = [[AddFriendVerifyViewController alloc] init];
                vc.identifier = model.memberNum;
                [self.navigationController pushViewController:vc animated:YES];
            } else if (addFriendOrChatType == AddFriendOrChatTypeChat) {
                //开始聊天
                [self beginChatWithIdentifier:model.name];
            }
        }];
        //去店铺
        [cell setGotoShopBlock:^{
            
        }];
        return cell;
    }
    return nil;
}


#pragma mark - tableview.delegate methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NearbyFriends *model = self.datas[indexPath.section];
    PersonalInfomationViewController *vc = [[PersonalInfomationViewController alloc] init];
    vc.friendId = model.memberId;
    vc.memberNum = model.memberNum;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - getter methods

- (DiscoveryHeaderView *)headerView {
    
    if (!_headerView) {
        _headerView = [[DiscoveryHeaderView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 435 + TJ_StatusBarHeight_Define)];
        _headerView.backgroundColor = [UIColor whiteColor];
    }
    return _headerView;
}


- (NSMutableArray *)datas{
    
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

- (NSArray *)acticles{
    
    if (!_acticles) {
        _acticles = [NSArray array];
    }
    return _acticles;
}


#pragma mark - override methods

- (void)registerTableViewCell
{
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.estimatedRowHeight = 297;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    UIView *footer = [[UIView alloc] init];
    footer.backgroundColor = mBackgroudColor;
    footer.frame = CGRectMake(0, 0, KScreenWidth, 10);
    self.tableView.tableFooterView = footer;
}

- (void)loadErrorData
{
    [super loadErrorData];
    self.baseNavView.hidden = YES;
}

- (void)loadNoData
{
    [super loadNoData];
    self.baseNavView.hidden = YES;
}


- (void)endLoadMore{
    [super endLoadMore];
    self.baseNavView.hidden = NO;
}

- (void)endRefresh{
    [super endRefresh];
    self.baseNavView.hidden = NO;
}

- (void)endLoadMoreMoData
{
    [super endLoadMoreMoData];
    self.baseNavView.hidden = NO;
}


@end

